﻿using System;
using Module.Core.LoginSystem.Commons;
using Module.Core.LoginSystem.Commons.Framwork;
using Module.Core.LoginSystem.Commons.Utilities;
using Module.Core.LoginSystem.Components.Audits;
using Module.Core.LoginSystem.Components.Modules;
using Module.Core.LoginSystem.Components.Roles;
using Module.Core.LoginSystem.Components.Users;
namespace Web.Cms.Users
{
    public partial class MyPassword : AdminUserControl
    {
        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            RolePermisionInfo _roleInfo =
                     RoleController.GetReadWritePermison(CurrentUser.UserID, CurrentCommand.CommandID);
            if (_roleInfo == null) return;
            if (_roleInfo.Write == 0)
            {
                btnUpdate.Visible = false;
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            if (!Page.IsValid) return;
            if (txtPassword.Text == string.Empty) return;
            if (CurrentUser.Password == SecurityUtility.MD5Encrypt(txtPassword.Text.Trim()))
            {
                if (SecurityUtility.MD5Encrypt(txtNewPasswordConfirm.Text.Trim()) == SecurityUtility.MD5Encrypt(txtNewPassword.Text.Trim()))
                {
                    try
                    {
                        CurrentUser.Password = SecurityUtility.MD5Encrypt(txtNewPassword.Text.Trim());
                        UserController.UpdateUser(CurrentUser);
                        lblUpdateStatus.Text = MiscUtility.MSG_UPDATE_SUCCESS;
                        // Insert Cores_Audits
                        ModuleInfo _moduleInfo = ModuleController.GetModule(CurrentCommand.CtrlKey);
                        AuditController.CreateAuditQ(_moduleInfo.ModuleDefID, (int)AuditCode.Update, CurrentCommand.CtrlKey, CurrentUser.UserID, CurrentUser.UserID
                                                    , "Thay đổi Password", 1, DateTime.Now);
                        Response.Redirect(UIProcess.DEFAULT_CP_PAGE);
                    }
                    catch (Exception ex)
                    {
                        lblUpdateStatus.Text = ex.Message;
                    }
                }

            }
            else
            {
                lblUpdateStatus.Text = "Bạn nhập sai mật khẩu cũ!";

            }
        }

        protected void btnBack_Click(object sender, EventArgs e)
        {
            Response.Redirect(UIProcess.DEFAULT_CP_PAGE);
        }
    }
}